import base64
from mitmproxy.http import HTTPFlow
import time
from mitmproxy.http import cookies as http_cookies
from ZiMoooModule.process_manage import get_process


def get_cookie_expires(timeStamp: float = None, MaxAge: float = None):
    x = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun'}
    m = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sept", 10: "Oct",
         11: "Nov", 12: "Dec"}
    if not timeStamp:
        timeStamp = time.time()
    if not MaxAge:
        MaxAge = 365 * 24 * 60 * 60
    timeStamp = timeStamp + MaxAge
    timeArray = time.localtime(timeStamp)
    s = time.strftime(", %d-YUE-%Y %H:%M:%S GMT", timeArray)
    s = x[timeArray.tm_wday + 1] + s
    s = s.replace("YUE", m[timeArray.tm_mon])
    return s


def flow_data_to_json(flow: HTTPFlow):
    request_data = {}
    request_data['method'] = flow.request.method
    request_data['url'] = flow.request.url
    request_data['urlencoded_form'] = []
    request_data['query'] = []
    if flow.request.urlencoded_form:
        for key in flow.request.urlencoded_form:
            value = flow.request.urlencoded_form.get(key)
            request_data['urlencoded_form'].append({"name": key, "value": value})
    if flow.request.query:
        for key in flow.request.query:
            value = flow.request.query.get(key)
            request_data['query'].append({"name": key, "value": value})

    request_data['cookies'] = []
    for key in flow.request.cookies:
        request_data['cookies'].append({key: flow.request.cookies.get(key)})
    request_data['headers'] = []
    for key in flow.request.headers:
        request_data['headers'].append({"name": key, "value": flow.request.headers.get(key)})
    if flow.request.method.upper() == "POST":
        request_data['data'] = base64.b64encode(flow.request.content).decode()

    response_data = {}
    if flow.response:
        response_data["cookies"] = []
        for key in flow.response.cookies:
            value = flow.response.cookies.get(key)
            ck = {}
            ck["name"] = key
            ck["value"] = value[0]
            for k in value[1].keys():
                ck[k] = value[1].get(k)
            response_data["cookies"].append(ck)
        response_data['headers'] = []
        for key in flow.response.headers:
            response_data['headers'].append({"name": key, "value": flow.response.headers.get(key)})
        response_data['code'] = flow.response.status_code
        response_data['data'] = base64.b64encode(flow.response.content).decode()

    return {"id": flow.id, "request": request_data, "response": response_data}


def get_flow_process(flow: HTTPFlow):
    try:
        port = int(flow.client_conn.peername[1])
        p = get_process(port=port)

        if p:
            pp = p.parent()
            process_info = {
                "flow_id": flow.id,
                "port": port,
                "pid": p.pid,
                "name": p.name(),
                "cmdline": p.cmdline(),
                "ppid": pp.pid,
                "ppname":pp.name(),
                "ppcmdline": pp.cmdline()
            }
            return process_info
        else:
            print(f"获取进程信息失败！")
            print(f"client_conn：{flow.client_conn.peername}.")
            print(f"server_conn：{flow.server_conn.peername}.")
            print(f"url：{flow.request.url}")
            return None
    except Exception as E:
        print(f"获取进程信息异常：{E}")
        print(f"client_conn：{flow.client_conn.peername}.")
        print(f"server_conn：{flow.server_conn.peername}.")
        print(f"url：{flow.request.url}")
        return None

if __name__ == '__main__':
    timeStamp = time.time()
    print(type(timeStamp))
